<i18n lang="json">
{
  "zh-cn": {
    "intro": "请绑定您的手机号 📱",
    "digSuccess":"已成功绑定手机号!",
    "successCode":"发送验证码成功!",
    "wxTitle": "完成手机绑定，即可一键登录纳维定位平台",
    "form": {
      "account": "手机号",
      "captcha": "验证码",
      "sendCaptcha": "发送验证码",
      "imgCaptcha":"图形验证码",
      "confirm": "绑定",
      "captchaCountdown": "{0} 秒后可重新发送"
    },
    "rules": {
      "account": "请输入手机号",
      "phone": "手机号格式错误",
      "captcha": "请输入验证码",
      "code": "请输入图形验证码"
    }
  },
  "en": {
    "intro": "FBind phone ❗️",
    "digSuccess" : "Successfully bound phone number",
    "successCode":"Successfully sent verification code",
    "wxTitle": "Once the binding is completed,log in to the Navier positioning platform",
    "form": {
      "account": "Account",
      "captcha": "Captcha",
      "sendCaptcha": "Send Captcha",
      "password": "New Password",
      "checkPassword": "Check Password",
      "imgCaptcha":"Graphic verification code",
      "confirm": "Confirm",
      "captchaCountdown": "Can resend in {0}s"
    },
    "rules": {
      "account": "Please enter an account",
      "captcha": "Please enter a captcha",
      "phone": "Phone number format error",
      "code": "Please enter a verification code"
    }
  }
}
</i18n>

<script setup lang="ts">
import apiUser from '@/api/modules/user'
import useSettingsStore from '@/store/modules/settings.ts'
import useUserStore from '@/store/modules/user.ts'
import { FormControl, FormField, FormItem, FormMessage } from '@/ui/shadcn/ui/form'
import storage from '@/utils/storage'
import { toTypedSchema } from '@vee-validate/zod'
import { useForm } from 'vee-validate'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'
import * as z from 'zod'

const { t } = useI18n()
const route = useRoute() // 获取路由实例
const router = useRouter()
const settingsStore = useSettingsStore()
const userStore = useUserStore()
const loading = ref(false)
const imgCaptcha = ref<string>('')
const redirect = ref(route.query.redirect?.toString() ?? settingsStore.settings.home.fullPath)
const uuid = ref<string>('')
const userImag = ref<any>(storage.local.get('avatar'))
// 获取图形验证码
async function getImgCaptcha() {
  apiUser.captchaImage().then((res: any) => {
    if (res.code === 200) {
      uuid.value = res.data.uuid
      refreshCaptcha(res.data.img)
    }
  })
}
// 获取验证码逻辑
async function refreshCaptcha(url: string) {
  try {
    imgCaptcha.value = `data:image/png;base64,${url}`
  }
  catch (error) {
    toast.error(t('codeTextError'))
  }
}

const form = useForm({
  validationSchema: toTypedSchema(
    z.object({
      phone: z.string().min(1, t('rules.account')).regex(/^\d{11}$/, t('rules.phone')),
      smsCode: z.string().min(4, t('rules.captcha')),
      code: z.string().min(1, t('rules.code')),
    }),
  ),
  initialValues: {
    phone: '',
    smsCode: '',
    code: '',
  },
})
const onSubmit = form.handleSubmit((values) => {
  loading.value = true
  const onResetData: any = {
    phone: values.phone,
    smsCode: values.smsCode,
    unionid: storage.local.get('unionid'),
  }
  userStore.loginBindPhone(onResetData).then((res: any) => {
    if (res.code === 200) {
      loading.value = false
      toast.success(t('digSuccess'))
      router.push(redirect.value)
    }
    else {
      loading.value = false
    }
  })
})

const countdown = ref(0)
const countdownInterval = ref(Number.NaN)
async function handleSendCaptcha(e: any) {
  e.preventDefault()
  e.stopPropagation()
  // 仅验证 username 和 code 字段
  const usernameValidation = await form.validateField('phone')
  const codeValidation = await form.validateField('code')
  if (!usernameValidation.valid) {
    return
  }
  if (!codeValidation.valid) {
    return
  }
  // // 仅验证 username 和 code 字段
  const phone = form.values.phone
  const captcha = form.values.code
  const registerSmsData = {
    phone: phone as string, // 类型断言
    uuid: uuid.value,
    captcha: captcha as string, // 类型断言
  }
  const res: any = await apiUser.sendSms(registerSmsData)
  if (res.code === 200) {
    toast.success(t('successCode'))
    countdown.value = 60
    countdownInterval.value = window.setInterval(() => {
      countdown.value--
      if (countdown.value === 0) {
        clearInterval(countdownInterval.value)
      }
    }, 1000)
  }

  else {
    await getImgCaptcha()
  }
}

onMounted(() => {
  getImgCaptcha()
})
</script>

<template>
  <div class="bind-container">
    <div class="bg-banner" />
    <div class="wrap">
      <div class="left_center p12">
        <div style="padding-top: 5rem">
          <p class="avatar pb-6">
            <img alt="" :src="userImag">
          </p>
          <p class="name pb-6">
            Hi,{{ storage.local.get('account') }}
          </p>
          <p class="pb-6">
            {{ t('wxTitle') }}
          </p>
          <p class="icons flex pt-6">
            <img alt="" src="@/assets/images/wxicon.png">
            <img alt="" src="@/assets/images/ljicon.png">
            <img class="logo" alt="" src="@/assets/images/bannerlogo.png">
          </p>
        </div>
      </div>
      <div class="min-h-500px flex-col-stretch-center p-12">
        <form @submit.prevent="onSubmit">
          <FaBlurReveal :delay="0.2" :duration="0.4" class="mb-8 space-y-2">
            <h3 class="text-4xl color-[var(--el-text-color-primary)] font-bold">
              {{ t('intro') }}
            </h3>
          </FaBlurReveal>
          <FormField v-slot="{ componentField, errors }" name="phone">
            <FormItem class="relative pb-6 space-y-0">
              <FormControl>
                <FaInput type="text" :placeholder="t('form.account')" class="w-full" :class="errors.length && 'border-destructive'" v-bind="componentField" />
              </FormControl>
              <Transition enter-active-class="transition-opacity" enter-from-class="opacity-0" leave-active-class="transition-opacity" leave-to-class="opacity-0">
                <FormMessage class="absolute bottom-1 text-xs" />
              </Transition>
            </FormItem>
          </FormField>
          <div class="flex-start-between gap-2">
            <FormField v-slot="{ componentField, errors }" name="code">
              <FormItem class="relative pb-6 space-y-0" style="width: 70%">
                <FormControl>
                  <FaInput type="text" :placeholder="t('form.imgCaptcha')" class="w-full" :class="errors.length && 'border-destructive'" v-bind="componentField" />
                </FormControl>
                <Transition enter-active-class="transition-opacity" enter-from-class="opacity-0" leave-active-class="transition-opacity" leave-to-class="opacity-0">
                  <FormMessage class="absolute bottom-1 text-xs" />
                </Transition>
              </FormItem>
            </FormField>
            <div style="width: 30%">
              <img :src="imgCaptcha" alt="imgCaptcha" class="w-img" @click="getImgCaptcha">
            </div>
          </div>
          <div class="flex-start-between gap-2">
            <FormField v-slot="{ componentField, value, setValue }" name="smsCode">
              <FormItem class="relative pb-6 space-y-0">
                <FormControl>
                  <FaPinInput :model-value="value" :name="componentField.name" :length="4" class="border-destructive" @update:model-value="val => setValue(val)" />
                </FormControl>
                <Transition enter-active-class="transition-opacity" enter-from-class="opacity-0" leave-active-class="transition-opacity" leave-to-class="opacity-0">
                  <FormMessage class="absolute bottom-1 text-xs" />
                </Transition>
              </FormItem>
            </FormField>
            <FaButton variant="outline" size="lg" :disabled="countdown > 0" class="flex-1 px-4" @click.stop="handleSendCaptcha">
              {{ countdown === 0 ? t('form.sendCaptcha') : t('form.captchaCountdown', [countdown]) }}
            </FaButton>
          </div>
          <FaButton :loading="loading" size="lg" class="mt-4 w-full" type="submit">
            {{ t('form.confirm') }}
          </FaButton>
        </form>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.w-img{
  width: 100%;
  height: 40px;
}
.bind-container{
  width: 100%;
  height: 100%;
  position: relative;
}
.bg-banner{
  position: fixed;
  z-index: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(closest-side, hsl(var(--border) / 10%) 30%, hsl(var(--primary) / 20%) 30%, hsl(var(--border) / 30%) 50%) no-repeat, radial-gradient(closest-side, hsl(var(--border) / 10%) 30%, hsl(var(--primary) / 20%) 30%, hsl(var(--border) / 30%) 50%) no-repeat;
  background-position: 100% 100%, 0 0;
  background-size: 200vw 200vh;
  filter: blur(100px);
  left: 0;
  top: 0;
  z-index: -1;
}
.wrap{
  width:50%;
  margin: 0 auto;
  background-color: hsl(var(--background));
  box-shadow: var(--un-ring-offset-shadow), var(--un-ring-shadow), var(--un-shadow);
  position: absolute;
  border-radius: calc(var(--radius) - 2px);
  --un-shadow: var(--un-shadow-inset) 0 4px 6px -1px var(--un-shadow-color, rgb(0 0 0 / 0.1)), var(--un-shadow-inset) 0 2px 4px -2px var(--un-shadow-color, rgb(0 0 0 / 0.1));
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  display: flex;
  justify-content: flex-start;
}
.left_center{
  width: 50%;
  text-align: center;
  padding-top: 2rem;
  background-color: hsl(var(--muted) / var(--un-bg-opacity));
  position: relative;
  .avatar{
    display: flex;
    justify-content: center;
    img{
      width: 6rem;
    }
  }
  &::before{
    position: absolute;
    width: 100%;
    height: 100%;
    content: "";
   background: radial-gradient(closest-side, hsl(var(--border) / 10%) 30%, hsl(var(--primary) / 20%) 30%, hsl(var(--border) / 30%) 50%) no-repeat, radial-gradient(closest-side, hsl(var(--border) / 10%) 30%, hsl(var(--primary) / 20%) 30%, hsl(var(--border) / 30%) 50%) no-repeat;
    background-position: 100% 100%, 0 0;
    filter: blur(100px);
    left: 0;
    top: 0;
    z-index: -1;
  }
  .name{
    font-size: 20px;
    font-weight: bold;
  }
  .icons{
    justify-content: space-between;
    margin: 0 auto;
    width: 50%;
    img{
      width: 2rem;
    }
    .logo{
      width: 2rem;
      height: 2rem;
      border-radius: 50%;
    }
  }
}
[data-mode="mobile"] {
  .wrap{
    width: 100%;
    height: 100%;
    display: block;
    h3{
      font-size: 20px !important;
    }
    .left_center{
      width: 100%;
      &::before{
        z-index: -1;
      }
    }
  }

}
</style>
